﻿#include "aifaceform.h"
#include "ui_aifaceform.h"
#include <QPushButton>
#include <QJsonObject>
#include <QJsonDocument>
#include "httpclient.h"
#include <QString>
#include "addaifaceform.h"
#include "AiPtuStruct.h"
#include "reviseaifaceform.h"
#include <QJsonArray>
#include "addchannelform.h"
#include "revisechannelform.h"
#include <QMessageBox>
#include "iconhelper.h"


AiFaceForm *AiFaceForm::pThis = nullptr;
AiFaceForm::AiFaceForm(const QString &ip, QWidget *parent) :
    QWidget(parent),
    ui(new Ui::AiFaceForm),
    m_ip(ip),
    current_page(0),
    current_page_2(0)

{
    ui->setupUi(this);
    this->initform();
    pThis = this;
}

AiFaceForm::~AiFaceForm()
{
    delete ui;
}
void AiFaceForm::initform()
{
    ui->stackedWidget->setCurrentIndex(0);
    QList<QToolButton *> btns;
    QList<int> pixChar;
    pixChar << 0xf007 << 0xf0c2  ;

    btns << ui->tbn_employee << ui->tbn_channel  ;
    QString normalBgColor = "rgb(12, 12, 12)";
    QString darkBgColor = "rgb(12, 12, 12)";
    QString normalTextColor = "#54626F";
    QString darkTextColor = "#086FF7";
    IconHelper::Instance()->setStyle(ui->widget, btns, pixChar, 24, 30, 30, "right", 3, "#029FEA", normalBgColor, darkBgColor, normalTextColor, darkTextColor);



    QStringList header;
    header << "ID" << "部门" << "姓名" << "员工编号" << "身份证号" << "联系方式" << "唯一标识" << "人脸图片存储位置";
    ui->tableWidget->setColumnCount(header.size());
    ui->tableWidget->setHorizontalHeaderLabels(header);
    for (int i = 0; i < header.size(); i++)
    {
        ui->tableWidget->setColumnWidth(i, 120);
    }
    ui->tableWidget->setColumnWidth(6, 180);
    ui->tableWidget->setColumnWidth(7, 100);
    ui->tableWidget->horizontalHeader()->setStretchLastSection(true);
    //  ui->tableWidget->setAlternatingRowColors(true);
    ui->tableWidget->verticalHeader()->setHidden(true);
    ui->tableWidget->setSelectionBehavior(QAbstractItemView::SelectRows);

    QStringList header1;
    header1 << "ID" << "设备类型" << "IPC IP" << "IPC 用户名" << "IPC 密码" << "IPC 流地址" << "语音播报地址" << "通道使能" << "通道预览";
    ui->tableWidget_2->setColumnCount(header1.size());
    ui->tableWidget_2->setHorizontalHeaderLabels(header1);
    for (int i = 0; i < header1.size(); i++)
    {
        ui->tableWidget_2->setColumnWidth(i, 120);
    }
    ui->tableWidget_2->setColumnWidth(6, 180);
    ui->tableWidget_2->setColumnWidth(7, 100);
    ui->tableWidget_2->horizontalHeader()->setStretchLastSection(true);
    //  ui->tableWidget->setAlternatingRowColors(true);
    ui->tableWidget_2->verticalHeader()->setHidden(true);
    ui->tableWidget_2->setSelectionBehavior(QAbstractItemView::SelectRows);


}




void AiFaceForm::on_search_employee_clicked()
{
    QString request_path = QString("http://%1:8800/api/face?limit=10&offset=0").arg(m_ip);
    HttpClient(request_path).success(on_search_employees).get();

}

void  AiFaceForm::on_search_employees(const QString &response)
{
    for(int row = pThis-> ui->tableWidget->rowCount() - 1; row >= 0; row--)
    {
        pThis->ui->tableWidget->removeRow(row);
    }
    QJsonDocument jsonDocument = QJsonDocument::fromJson(response.toUtf8().data());
    if( jsonDocument.isNull() )
    {
        qDebug() << "===> please check the string " << response.toUtf8().data();
    }
    QJsonObject jsonObject = jsonDocument.object();
    jsonObject.value("total").toInt() % jsonObject.value("limit").toInt() == 0
    ? pThis->total_pages = jsonObject.value("total").toInt() / jsonObject.value("limit").toInt() : pThis->total_pages = jsonObject.value("total").toInt() / jsonObject.value("limit").toInt() + 1;
    if(!jsonObject.value("offset").toInt()) pThis->current_page = 1;
    pThis->ui->led_page->setText(QString("%1/%2").arg(pThis->current_page).arg(pThis->total_pages));
    QJsonArray jsonArray = jsonObject.value("items").toArray();
    int count = jsonArray.count();
    if (pThis == NULL) return;
    for (int i = 0; i < count; i++)
    {
        QJsonObject json = jsonArray.at(i).toObject();
        int row = pThis->ui->tableWidget->rowCount();
        pThis-> ui->tableWidget->insertRow(row);
        pThis-> ui->tableWidget->setItem(row, 0, new QTableWidgetItem(QString::number(json.value("id").toInt())));
        pThis-> ui->tableWidget->setItem(row, 1, new QTableWidgetItem(json.value("department").toString()));
        pThis-> ui->tableWidget->setItem(row, 2, new QTableWidgetItem(json.value("name").toString()));
        pThis-> ui->tableWidget->setItem(row, 3, new QTableWidgetItem(json.value("work_number").toString() ));
        pThis-> ui->tableWidget->setItem(row, 4, new QTableWidgetItem(json.value("id_number").toString()));
        pThis-> ui->tableWidget->setItem(row, 5, new QTableWidgetItem(json.value("phone").toString()));
        pThis-> ui->tableWidget->setItem(row, 6, new QTableWidgetItem(json.value("uuid").toString()));
        pThis-> ui->tableWidget->setItem(row, 7, new QTableWidgetItem(json.value("face_image_path").toString()));
    }
#if TEST
#endif
    qDebug() << "receive success!";
//    qDebug() << jsonObject.value("limit").toInt();
//    qDebug() << jsonObject.value("offset").toInt();
//    qDebug() << jsonObject.value("total").toInt();
}



void AiFaceForm::on_add_employee_clicked()
{
    AddAifaceForm *aiface = new AddAifaceForm(m_ip);
    connect(aiface, &AddAifaceForm::sig_clear, [this]
    {
        this->on_search_employee_clicked();
    });
    aiface->show();
}


void AiFaceForm::on_revise_employee_clicked()
{
    int row = ui->tableWidget->currentRow();
    if(row < 0)return;
    AiFaceParam param;
    param.id = ui->tableWidget->item(row, 0)->text().toInt();
    param.department = ui->tableWidget->item(row, 1)->text();
    param.name = ui->tableWidget->item(row, 2)->text();
    param.work_number = ui->tableWidget->item(row, 3)->text();
    param.id_number = ui->tableWidget->item(row, 4)->text();
    param.phone = ui->tableWidget->item(row, 5)->text();
    ReviseAiFaceForm *reviseform = new ReviseAiFaceForm(param, m_ip);
    connect(reviseform, &ReviseAiFaceForm::sig_clear, [this]
    {
        this->on_search_employee_clicked();
    });
    reviseform->show();
}


void AiFaceForm::on_delete_employee_clicked()
{
    int row = ui->tableWidget->currentRow();
    if(row < 0)return;
    QString id = ui->tableWidget->item(row, 0)->text();
    QString request_path = QString("http://%1:8800/api/face/%2").arg(m_ip).arg(id);
    HttpClient(request_path).success([this](const QString & response)
    {
        QJsonDocument jsonDocument = QJsonDocument::fromJson(response.toUtf8().data());
        if( jsonDocument.isNull() )
        {
            qDebug() << "===> please check the string " << response.toUtf8().data();
            return ;
        }
        QJsonObject jsonObject = jsonDocument.object();
        if(jsonObject["message"].toString() == "成功")
        {
            if(QMessageBox::information(pThis, tr("通知"), tr("删除成功"), QMessageBox::Ok, QMessageBox::NoButton))
            {
                this->on_search_employee_clicked();
                return;
            }
        }
    }).remove();
}


void AiFaceForm::on_search_channel_clicked()
{
    QString request_path = QString("http://%1:8800/api/config/channel?limit=10&offset=0").arg(m_ip);
    HttpClient(request_path).success(on_search_channel).get();
}


void AiFaceForm::on_search_channel(const QString &response)
{
    for(int row = pThis-> ui->tableWidget_2->rowCount() - 1; row >= 0; row--)
    {
        pThis->ui->tableWidget_2->removeRow(row);
    }
    QJsonDocument jsonDocument = QJsonDocument::fromJson(response.toUtf8().data());
    if( jsonDocument.isNull() )
    {
        qDebug() << "===> please check the string " << response.toUtf8().data();
    }
    QJsonObject jsonObject = jsonDocument.object();
    jsonObject.value("total").toInt() % jsonObject.value("limit").toInt() == 0
    ? pThis->total_pages_2 = jsonObject.value("total").toInt() / jsonObject.value("limit").toInt() : pThis->total_pages_2 = jsonObject.value("total").toInt() / jsonObject.value("limit").toInt() + 1;
    if(!jsonObject.value("offset").toInt()) pThis->current_page_2 = 1;
    pThis->ui->led_page_2->setText(QString("%1/%2").arg(pThis->current_page_2).arg(pThis->total_pages_2));
    QJsonArray jsonArray = jsonObject.value("items").toArray();
    int count = jsonArray.count();
    if (pThis == NULL) return;
    for (int i = 0; i < count; i++)
    {
        QJsonObject json = jsonArray.at(i).toObject();
        int row = pThis->ui->tableWidget_2->rowCount();
        pThis-> ui->tableWidget_2->insertRow(row);
        pThis-> ui->tableWidget_2->setItem(row, 0, new QTableWidgetItem(QString::number(json.value("id").toInt())));
        json.value("dev_type").toInt() == 0 ? pThis-> ui->tableWidget_2->setItem(row, 1, new QTableWidgetItem("海康")) : pThis-> ui->tableWidget_2->setItem(row, 1, new QTableWidgetItem("大华"));
        pThis-> ui->tableWidget_2->setItem(row, 2, new QTableWidgetItem(json.value("ip").toString() ));
        pThis-> ui->tableWidget_2->setItem(row, 3, new QTableWidgetItem(json.value("username").toString()));
        pThis-> ui->tableWidget_2->setItem(row, 4, new QTableWidgetItem(json.value("password").toString()));
        pThis-> ui->tableWidget_2->setItem(row, 5, new QTableWidgetItem(json.value("url").toString()));
        pThis-> ui->tableWidget_2->setItem(row, 6, new QTableWidgetItem(json.value("voice_ip").toString()));
        json.value("enable").toInt() == 0 ? pThis-> ui->tableWidget_2->setItem(row, 7, new QTableWidgetItem("非使能")) : pThis-> ui->tableWidget_2->setItem(row, 7, new QTableWidgetItem("使能"));
        json.value("preview").toInt() == 0 ? pThis-> ui->tableWidget_2->setItem(row, 8, new QTableWidgetItem("非预览")) : pThis-> ui->tableWidget_2->setItem(row, 8, new QTableWidgetItem("预览"));
    }
}

void AiFaceForm::on_tbn_channel_clicked()
{
    ui->stackedWidget->setCurrentIndex(1);
}

void AiFaceForm::on_tbn_employee_clicked()
{
    ui->stackedWidget->setCurrentIndex(0);
}

void AiFaceForm::on_add_channel_clicked()
{
    AddChannelForm *addchannel = new AddChannelForm(m_ip);
    connect(addchannel, &AddChannelForm::sig_clear, [this]
    {
        this->on_search_channel_clicked();
    });
    addchannel->show();
}

void AiFaceForm::on_revise_channel_clicked()
{
    int row = ui->tableWidget_2->currentRow();
    if(row < 0)return;
    AiChannelParam param;
    param.id = ui->tableWidget_2->item(row, 0)->text().toInt();
    ui->tableWidget_2->item(row, 1)->text() == "海康" ? param.dev_type = 0 : param.dev_type = 1;
    param.ip = ui->tableWidget_2->item(row, 2)->text();
    param.username = ui->tableWidget_2->item(row, 3)->text();
    param.password = ui->tableWidget_2->item(row, 4)->text();
    param.url = ui->tableWidget_2->item(row, 5)->text();
    param.voice_ip = ui->tableWidget_2->item(row, 6)->text();
    ui->tableWidget_2->item(row, 7)->text() == "使能" ? param.enable = 1 : param.enable = 0;
    ui->tableWidget_2->item(row, 8)->text() == "预览" ? param.preview = 1 : param.preview = 0;
    ReviseChannelForm *revisechannel = new ReviseChannelForm(param, m_ip);
    connect(revisechannel, &ReviseChannelForm::sig_clear, [this]
    {
        this->on_search_channel_clicked();
    });
    revisechannel->show();
}

void AiFaceForm::on_delete_channel_clicked()
{
    int row = ui->tableWidget_2->currentRow();
    if(row < 0)return;
    QString id = ui->tableWidget_2->item(row, 0)->text();
    QString request_path = QString("http://%1:8800/api/config/channel/%2").arg(m_ip).arg(id);
    HttpClient(request_path).success([this](const QString & response)
    {
        QJsonDocument jsonDocument = QJsonDocument::fromJson(response.toUtf8().data());
        if( jsonDocument.isNull() )
        {
            qDebug() << "===> please check the string " << response.toUtf8().data();
            return ;
        }
        QJsonObject jsonObject = jsonDocument.object();
        if(jsonObject["message"].toString() == "成功")
        {
            if(QMessageBox::information(pThis, tr("通知"), tr("删除成功"), QMessageBox::Ok, QMessageBox::NoButton))
            {
                this->on_search_channel_clicked();
                return;
            }
        }
    }).remove();
}

void AiFaceForm::on_reset_employee_clicked()
{
    int ret = 0;
    if(ret = QMessageBox::question(pThis, tr("通知"), tr("确定重置员工库？"), QMessageBox::Ok, QMessageBox::Cancel))
    {
        if(ret == QMessageBox::Cancel)          return;
        else
        {
            QString request_path = QString("http://%1:8800/api/faceReset").arg(m_ip);
            HttpClient(request_path).success([this](const QString & response)
            {
                this->on_search_employee_clicked();
                qDebug() << response;
            }).post();
        }

    }
}


void AiFaceForm::on_btn_page_up_clicked()
{
    if(current_page <= 1)return;
    current_page -= 1;
    QString request_path = QString("http://%1:8800/api/face?limit=10&offset=%2").arg(m_ip).arg((current_page - 1) * 10);
    HttpClient(request_path).success(on_search_employees).get();
}

void AiFaceForm::on_btn_page_down_clicked()
{
    if(current_page == total_pages)return;
    QString request_path = QString("http://%1:8800/api/face?limit=10&offset=%2").arg(m_ip).arg(current_page * 10);
    current_page += 1;
    HttpClient(request_path).success(on_search_employees).get();
}

void AiFaceForm::on_btn_page_up_2_clicked()
{
    if(current_page_2 <= 1)return;
    current_page_2 -= 1;
    QString request_path = QString("http://%1:8800/api/config/channel?limit=10&offset=%2").arg(m_ip).arg((current_page_2 - 1) * 10);
    HttpClient(request_path).success(on_search_channel).get();


}


void AiFaceForm::on_btn_page_down_2_clicked()
{
    if(current_page_2 == total_pages_2)return;
    QString request_path = QString("http://%1:8800/api/config/channel?limit=10&offset=%2").arg(m_ip).arg(current_page_2 * 10);
    current_page_2 += 1;
    HttpClient(request_path).success(on_search_channel).get();
}
